import React, { useState, useEffect, useRef } from 'react';
import { 
  Card, Form, Input, Button, Table, Typography, Divider, Space, 
  Row, Col, Modal, List, Popconfirm, message, Tabs, Empty, 
  Tag, Descriptions, Statistic, Collapse, DatePicker, Alert, Switch, Select
} from 'antd';
import { 
  PlusOutlined, DeleteOutlined, EditOutlined, 
  LineChartOutlined, SaveOutlined, ReloadOutlined, PlayCircleOutlined, EyeOutlined
} from '@ant-design/icons';
import * as echarts from 'echarts';
import { strategyCombinationApi } from '../../api';
import './index.css';
import moment from 'moment';
import axios from 'axios';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;

// 环境检测和配置
const isProduction = process.env.NODE_ENV === 'production' || 
                    window.location.hostname === 'zhangtao.live' ||
                    window.location.hostname.includes('zhangtao.live');

const baseURL = isProduction ? 'http://zhangtao.live:5001' : '';

// 收益曲线图组件
const ReturnsChart = ({ cumulativeReturns }) => {
  const chartRef = useRef(null);
  
  useEffect(() => {
    // 确保DOM已加载
    if (chartRef.current && cumulativeReturns && cumulativeReturns.length > 0) {
      // 初始化图表
      const chartInstance = echarts.init(chartRef.current);
      
      // 准备数据
      const dates = cumulativeReturns.map(item => item.date);
      const values = cumulativeReturns.map(item => ((item.cumulative_return - 1) * 100).toFixed(2));
      
      // 计算Y轴范围
      const numValues = values.map(v => parseFloat(v));
      const maxValue = Math.max(...numValues);
      const minValue = Math.min(...numValues);
      const yAxisPadding = Math.max(Math.abs(maxValue), Math.abs(minValue)) * 0.1;
      
      // 图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const date = moment(params[0].axisValue).format('YYYY-MM-DD');
            const value = params[0].data;
            return `${date}<br/>组合收益: ${value}%`;
          }
        },
        legend: {
          data: ['组合收益', '基准线'],
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          boundaryGap: false,
          axisLabel: {
            formatter: function(value) {
              return moment(value).format('YYYY-MM-DD');
            }
          }
        },
        yAxis: {
          type: 'value',
          min: Math.floor(minValue - yAxisPadding),
          max: Math.ceil(maxValue + yAxisPadding),
          axisLabel: {
            formatter: '{value}%'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '组合收益',
            type: 'line',
            data: numValues,
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#5B8FF9'
            },
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#5B8FF9',
              borderColor: '#fff',
              borderWidth: 2
            }
          },
          {
            name: '基准线',
            type: 'line',
            data: Array(dates.length).fill(0),
            lineStyle: {
              width: 2,
              color: '#d9d9d9',
              type: 'dashed'
            },
            symbol: 'none'
          }
        ]
      };
      
      // 设置配置项并渲染图表
      chartInstance.setOption(option);
      
      // 响应窗口大小变化
      const resizeHandler = () => {
        chartInstance.resize();
      };
      window.addEventListener('resize', resizeHandler);
      
      // 组件卸载时清理
      return () => {
        window.removeEventListener('resize', resizeHandler);
        chartInstance.dispose();
      };
    }
  }, [cumulativeReturns]);
  
  return (
    <div className="returns-chart">
      <div ref={chartRef} style={{ width: '100%', height: '400px' }}></div>
    </div>
  );
};

const StrategyCombination = () => {
  const [combinations, setCombinations] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCombination, setEditingCombination] = useState(null);
  const [selectedCombination, setSelectedCombination] = useState(null);
  const [combinationHoldings, setCombinationHoldings] = useState(null);
  const [holdingsLoading, setHoldingsLoading] = useState(false);
  const [backTestResults, setBackTestResults] = useState(null);
  const [backTestLoading, setBackTestLoading] = useState(false);
  const [backTestStartDate, setBackTestStartDate] = useState(null);
  const [useRealData, setUseRealData] = useState(false);
  const [isAutoBacktest, setIsAutoBacktest] = useState(false);
  const [holdingsStartDate, setHoldingsStartDate] = useState(null);
  
  const [form] = Form.useForm();
  
  // 加载所有策略组合
  const fetchCombinations = async () => {
    setLoading(true);
    try {
      const data = await strategyCombinationApi.getAllCombinations();
      setCombinations(data || []);
    } catch (error) {
      console.error('获取策略组合失败:', error);
      message.error('获取策略组合失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 加载组合持仓
  const fetchCombinationHoldings = async (combinationId) => {
    setHoldingsLoading(true);
    try {
      const startDate = holdingsStartDate ? moment(holdingsStartDate).format('YYYY-MM-DD') : null;
      const data = await strategyCombinationApi.getCombinationHoldings(combinationId, startDate, useRealData);
      setCombinationHoldings(data);
    } catch (error) {
      console.error('获取组合持仓失败:', error);
      message.error('获取组合持仓失败');
    } finally {
      setHoldingsLoading(false);
    }
  };
  
  // 运行组合回测
  const runCombinationBacktest = async (combinationId) => {
    setBackTestLoading(true);
    try {
      // 获取回测参数
      const params = {
        is_real: useRealData
      };
      
      // 处理日期参数
      if (backTestStartDate) {
        // 确保日期是有效的
        const validDate = moment(backTestStartDate);
        if (validDate.isValid()) {
          params.start_date = validDate.format('YYYY-MM-DD HH:mm:ss');
          console.log('使用开始日期:', params.start_date);
        }
      }
      
      console.log('发送参数:', JSON.stringify(params));
      
      // 确保组合ID是数字
      const numericCombinationId = Number(combinationId);
      
      // 直接使用axios发送请求
      const response = await axios.post(`${baseURL}/strategy_combinations/${numericCombinationId}/backtest`, params, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      const data = response.data;
      console.log('回测结果:', data);
      setBackTestResults(data);
      setIsAutoBacktest(false);
      message.success('回测完成');
    } catch (error) {
      console.error('运行组合回测失败:', error);
      setIsAutoBacktest(false);
      message.error('运行组合回测失败: ' + (error.message || '未知错误'));
    } finally {
      setBackTestLoading(false);
    }
  };
  
  // 运行单个策略回测
  const runSingleStrategyBacktest = async (strategy, position) => {
    try {
      // 获取回测参数
      const params = {
        is_real: useRealData
      };
      
      // 处理日期参数
      if (backTestStartDate) {
        const validDate = moment(backTestStartDate);
        if (validDate.isValid()) {
          params.start_date = validDate.format('YYYY-MM-DD HH:mm:ss');
        }
      }
      
      // 使用策略参数进行回测
      const strategyParams = {
        ...strategy.parameters,
        isReal: useRealData,
        startDate: params.start_date
      };
      
      console.log('运行单个策略回测:', strategy.strategy_name, strategyParams);
      
      // 调用单个策略回测接口
      const response = await axios.post(`${baseURL}/back`, strategyParams, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      const data = response.data;
      console.log('单个策略回测结果:', data);
      
      // 显示回测结果
      Modal.info({
        title: `${strategy.strategy_name} 回测结果${position ? ` - ${position.code}` : ''}`,
        width: 800,
        maskClosable: true,
        content: (
          <div>
            <Descriptions bordered size="small" column={2}>
              <Descriptions.Item label="策略名称">{strategy.strategy_name}</Descriptions.Item>
              {position && <Descriptions.Item label="股票代码">{position.code}</Descriptions.Item>}
              {position && <Descriptions.Item label="买入价格">{position.price?.toFixed(2)}</Descriptions.Item>}
              {position && <Descriptions.Item label="持仓日期">{moment(position.date).format('YYYY-MM-DD')}</Descriptions.Item>}
            </Descriptions>
            
            <Divider orientation="left">交易记录</Divider>
            <Table 
              dataSource={data.trade_log?.slice().reverse() || []} 
              rowKey={(record, index) => index}
              pagination={{ pageSize: 5 }}
              size="small"
              columns={[
                { title: '日期', dataIndex: 'date', key: 'date', 
                  render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss') },
                { title: '类型', dataIndex: 'type', key: 'type',
                  render: (text) => (
                    <Tag color={text === 'buy' ? 'green' : 'red'}>
                      {text === 'buy' ? '买入' : '卖出'}
                    </Tag>
                  ) },
                { title: '股票代码', dataIndex: 'code', key: 'code' },
                { title: '价格', dataIndex: 'price', key: 'price' },
                { title: '说明', dataIndex: 'desc', key: 'desc' }
              ]} 
            />
            
            {data.cumulative_returns && data.cumulative_returns.length > 0 && (
              <>
                <Divider orientation="left">收益曲线</Divider>
                <ReturnsChart cumulativeReturns={data.cumulative_returns} />
              </>
            )}
          </div>
        ),
        onOk() {
          console.log('关闭单个策略回测结果');
        },
      });
      
      message.success(`${strategy.strategy_name} 回测完成`);
    } catch (error) {
      console.error('运行单个策略回测失败:', error);
      message.error('运行单个策略回测失败: ' + (error.message || '未知错误'));
    }
  };
  
  // 显示持有特定股票的策略详情
  const showStockStrategyDetails = (position) => {
    // 找到持有该股票的所有策略
    const holdingStrategies = combinationHoldings.strategies_holdings.filter(strategy => 
      strategy.positions.some(pos => pos.code === position.code)
    );
    
    Modal.info({
      title: `${position.code} 持有策略详情`,
      width: 800,
      maskClosable: true,
      content: (
        <div>
          <Descriptions bordered size="small" column={2}>
            <Descriptions.Item label="股票代码">{position.code}</Descriptions.Item>
            <Descriptions.Item label="持有占比">{position.weight?.toFixed(1)}%</Descriptions.Item>
            <Descriptions.Item label="策略数量">{position.strategy_count}</Descriptions.Item>
            <Descriptions.Item label="买入价格">{position.price?.toFixed(2)}</Descriptions.Item>
          </Descriptions>
          
          <Divider orientation="left">持有策略列表</Divider>
          <List
            dataSource={holdingStrategies}
            renderItem={(strategy, index) => (
              <List.Item
                actions={[
                  <Button 
                    type="link" 
                    size="small"
                    onClick={() => {
                      const strategyPosition = strategy.positions.find(pos => pos.code === position.code);
                      if (strategyPosition) {
                        runSingleStrategyBacktest(strategy, strategyPosition);
                      }
                    }}
                  >
                    运行回测
                  </Button>
                ]}
              >
                <List.Item.Meta
                  title={`${strategy.strategy_name} (收益率: ${strategy.return?.toFixed(2)}%)`}
                  description={
                    <div>
                      <div>策略参数: {JSON.stringify(strategy.parameters, null, 2)}</div>
                      <div>持仓日期: {moment(position.date).format('YYYY-MM-DD')}</div>
                      <div>持仓股票: {position.code}</div>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        </div>
      ),
      onOk() {
        console.log('关闭股票策略详情');
      },
    });
  };
  
  // 显示策略交易记录
  const showStrategyTradeRecords = async (strategy) => {
    try {
      // 获取回测参数
      const params = {
        is_real: useRealData
      };
      
      // 处理日期参数
      if (backTestStartDate) {
        const validDate = moment(backTestStartDate);
        if (validDate.isValid()) {
          params.start_date = validDate.format('YYYY-MM-DD HH:mm:ss');
        }
      }
      
      // 使用策略参数进行回测
      const strategyParams = {
        ...strategy.parameters,
        isReal: useRealData,
        startDate: params.start_date
      };
      
      console.log('获取策略交易记录:', strategy.strategy_name, strategyParams);
      
      // 调用单个策略回测接口
      const response = await axios.post(`${baseURL}/back`, strategyParams, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      const data = response.data;
      console.log('策略交易记录:', data);
      
      // 显示交易记录
      Modal.info({
        title: `${strategy.strategy_name} 交易记录`,
        width: 1000,
        maskClosable: true,
        content: (
          <div>
            <Descriptions bordered size="small" column={2}>
              <Descriptions.Item label="策略名称">{strategy.strategy_name}</Descriptions.Item>
              <Descriptions.Item label="策略参数">
                <pre style={{ fontSize: '12px', maxHeight: '100px', overflow: 'auto' }}>
                  {JSON.stringify(strategy.parameters, null, 2)}
                </pre>
              </Descriptions.Item>
            </Descriptions>
            
            {data.trade_log && data.trade_log.length > 0 ? (
              <>
                <Divider orientation="left">交易记录</Divider>
                <Table 
                  dataSource={data.trade_log?.slice().reverse() || []} 
                  rowKey={(record, index) => index}
                  pagination={{ pageSize: 15 }}
                  size="small"
                  columns={[
                    { title: '日期', dataIndex: 'date', key: 'date', 
                      render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss') },
                    { title: '类型', dataIndex: 'type', key: 'type',
                      render: (text) => (
                        <Tag color={text === 'buy' ? 'green' : 'red'}>
                          {text === 'buy' ? '买入' : '卖出'}
                        </Tag>
                      ) },
                    { title: '股票代码', dataIndex: 'code', key: 'code' },
                    { title: '价格', dataIndex: 'price', key: 'price' },
                    { title: '说明', dataIndex: 'desc', key: 'desc' }
                  ]} 
                />
              </>
            ) : (
              <Empty description="暂无交易记录" />
            )}
            
            {data.cumulative_returns && data.cumulative_returns.length > 0 && (
              <>
                <Divider orientation="left">收益曲线</Divider>
                <ReturnsChart cumulativeReturns={data.cumulative_returns} />
              </>
            )}
          </div>
        ),
        onOk() {
          console.log('关闭策略交易记录');
        },
      });
      
      message.success(`${strategy.strategy_name} 交易记录加载完成`);
    } catch (error) {
      console.error('获取策略交易记录失败:', error);
      message.error('获取策略交易记录失败: ' + (error.message || '未知错误'));
    }
  };
  
  // 初始加载
  useEffect(() => {
    fetchCombinations();
  }, []);
  
  // 选择组合后加载持仓
  useEffect(() => {
    if (selectedCombination !== null) {
      fetchCombinationHoldings(selectedCombination);
    }
  }, [selectedCombination]);
  
  // 打开创建/编辑模态框
  const showModal = (combination = null) => {
    setEditingCombination(combination);
    form.resetFields();
    
    if (combination) {
      form.setFieldsValue({
        name: combination.name,
        strategies: JSON.stringify(combination.strategies, null, 2)
      });
    }
    
    setModalVisible(true);
  };
  
  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
  };
  
  // 保存组合
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      // 解析strategies字段的JSON字符串
      let strategies = [];
      try {
        strategies = JSON.parse(values.strategies);
        if (!Array.isArray(strategies)) {
          throw new Error('策略列表必须是数组');
        }
      } catch (err) {
        message.error('策略列表JSON格式不正确: ' + err.message);
        return;
      }
      
      const combinationData = {
        name: values.name,
        strategies: strategies
      };
      
      if (editingCombination) {
        // 更新现有组合
        await strategyCombinationApi.updateCombination(
          combinations.findIndex(c => c.name === editingCombination.name),
          combinationData
        );
        message.success('策略组合更新成功');
      } else {
        // 创建新组合
        await strategyCombinationApi.addCombination(combinationData);
        message.success('策略组合创建成功');
      }
      
      // 刷新列表
      fetchCombinations();
      setModalVisible(false);
    } catch (error) {
      console.error('保存策略组合失败:', error);
      message.error('保存策略组合失败');
    }
  };
  
  // 删除组合
  const handleDelete = async (combinationId) => {
    try {
      await strategyCombinationApi.deleteCombination(combinationId);
      message.success('策略组合删除成功');
      
      // 刷新列表
      fetchCombinations();
      
      // 如果删除的是当前选中的组合，清除选择
      if (selectedCombination === combinationId) {
        setSelectedCombination(null);
        setCombinationHoldings(null);
      }
    } catch (error) {
      console.error('删除策略组合失败:', error);
      message.error('删除策略组合失败');
    }
  };
  
  // 组合列表表格列定义
  const columns = [
    {
      title: '组合名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '策略数量',
      dataIndex: 'strategies',
      key: 'strategyCount',
      render: (strategies) => strategies?.length || 0
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record, index) => (
        <Space size="middle">
          <Button 
            type="primary" 
            size="small" 
            onClick={() => setSelectedCombination(index)}
          >
            查看
          </Button>
          <Button 
            size="small" 
            icon={<EditOutlined />} 
            onClick={() => showModal(record)}
          />
          <Popconfirm
            title="确定要删除这个策略组合吗？"
            onConfirm={() => handleDelete(index)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              danger 
              size="small" 
              icon={<DeleteOutlined />} 
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];
  
  // 渲染组合详情
  const renderCombinationDetails = () => {
    if (selectedCombination === null) {
      return (
        <Empty description="请选择一个策略组合" />
      );
    }
    
    if (holdingsLoading) {
      return (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Text>加载中...</Text>
        </div>
      );
    }
    
    if (!combinationHoldings) {
      return (
        <Empty description="无法加载组合数据" />
      );
    }
    
    return (
      <div className="combination-details">
        <Tabs defaultActiveKey="holdings" onChange={(activeKey) => {
          // 当切换到回测结果tab时，自动运行回测
          if (activeKey === 'backtest' && selectedCombination !== null) {
            // 如果没有回测结果，自动运行回测
            if (!backTestResults) {
              setIsAutoBacktest(true);
              message.info('正在自动运行回测...');
              runCombinationBacktest(selectedCombination);
            }
          }
        }}>
          <TabPane tab="组合持仓" key="holdings">
            <Card title="组合总览" style={{ marginBottom: '20px' }}>
              <div style={{ marginBottom: '16px' }}>
                <Space>
                  <span>开始时间：</span>
                  <DatePicker
                    value={holdingsStartDate}
                    onChange={setHoldingsStartDate}
                    placeholder="选择开始时间（可选）"
                    allowClear
                    style={{ width: 200 }}
                  />
                  <Switch
                    checkedChildren="实盘"
                    unCheckedChildren="历史"
                    checked={useRealData}
                    onChange={setUseRealData}
                    title="选择数据源"
                  />
                  <Button 
                    type="primary" 
                    onClick={() => fetchCombinationHoldings(selectedCombination)}
                    loading={holdingsLoading}
                  >
                    刷新持仓
                  </Button>
                </Space>
              </div>
              <Descriptions bordered size="small">
                <Descriptions.Item label="组合名称">{combinationHoldings.name}</Descriptions.Item>
                <Descriptions.Item label="创建时间">{moment(combinationHoldings.created_at).format('YYYY-MM-DD HH:mm')}</Descriptions.Item>
                <Descriptions.Item label="更新时间">{moment(combinationHoldings.updated_at).format('YYYY-MM-DD HH:mm')}</Descriptions.Item>
                <Descriptions.Item label="策略数量">{combinationHoldings.strategies_holdings?.length || 0}</Descriptions.Item>
                <Descriptions.Item label="数据源">
                  <Tag color={useRealData ? 'green' : 'blue'}>
                    {useRealData ? '实盘数据' : '历史数据'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="总收益率">
                  <Statistic
                    value={combinationHoldings.total_return || 0}
                    precision={2}
                    valueStyle={{ color: (combinationHoldings.total_return || 0) >= 0 ? '#3f8600' : '#cf1322' }}
                    suffix="%"
                  />
                </Descriptions.Item>
                <Descriptions.Item label="持仓股票数">{combinationHoldings.total_positions?.length || 0}</Descriptions.Item>
                {combinationHoldings.start_date && (
                  <Descriptions.Item label="回测开始时间">
                    {moment(combinationHoldings.start_date).format('YYYY-MM-DD')}
                  </Descriptions.Item>
                )}
                <Descriptions.Item label="持仓分布">
                  {combinationHoldings.total_positions && combinationHoldings.total_positions.length > 0 ? (
                    <div>
                      {combinationHoldings.total_positions.map((pos, index) => (
                        <Tag key={index} color="blue">
                          {pos.code}: {pos.weight?.toFixed(1)}%
                        </Tag>
                      ))}
                    </div>
                  ) : (
                    <Text type="secondary">无持仓</Text>
                  )}
                </Descriptions.Item>
              </Descriptions>
            </Card>
            
            <Card title="组合总持仓" style={{ marginBottom: '20px' }}>
              <div style={{ marginBottom: '10px', fontSize: '12px', color: '#666' }}>
                提示：点击持仓行或"查看策略"按钮可查看持有该股票的策略详情
              </div>
              {combinationHoldings.total_positions && combinationHoldings.total_positions.length > 0 ? (
                <Table 
                  dataSource={combinationHoldings.total_positions} 
                  rowKey={(record, index) => index}
                  pagination={false}
                  size="small"
                  onRow={(record, index) => ({
                    onClick: () => {
                      // 点击总持仓时显示持有该股票的策略详情
                      showStockStrategyDetails(record);
                    },
                    style: { cursor: 'pointer' }
                  })}
                  columns={[
                    { title: '股票代码', dataIndex: 'code', key: 'code' },
                    { title: '持有占比', dataIndex: 'weight', key: 'weight',
                      render: (text, record) => (
                        <div>
                          <div style={{ fontWeight: 'bold', color: '#1890ff' }}>
                            {text ? text.toFixed(1) : '0'}%
                          </div>
                          <div style={{ fontSize: '12px', color: '#999' }}>
                            {record.strategy_count || 0}/{combinationHoldings.strategies_holdings?.length || 0} 策略持有
                          </div>
                        </div>
                      ) },
                    { title: '买入价格', dataIndex: 'price', key: 'price',
                      render: (text) => text ? text.toFixed(2) : '-' },
                    { title: '最新持仓日期', dataIndex: 'date', key: 'date', 
                      render: (text) => text ? moment(text).format('YYYY-MM-DD') : '-' },
                    { title: '操作', key: 'action',
                      render: (_, record) => (
                        <Button 
                          type="link" 
                          size="small"
                          onClick={(e) => {
                            e.stopPropagation();
                            showStockStrategyDetails(record);
                          }}
                        >
                          查看策略
                        </Button>
                      ) }
                  ]} 
                />
              ) : (
                <Empty description="暂无持仓" />
              )}
            </Card>
            
            <Card title="策略持仓明细">
              <Collapse defaultActiveKey={['0']}>
                {combinationHoldings.strategies_holdings?.map((strategy, index) => (
                  <Panel 
                    header={
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
                        <span>{strategy.strategy_name} (收益率: {strategy.return.toFixed(2)}%)</span>
                        <div>
                          <Button 
                            type="primary" 
                            size="small"
                            icon={<LineChartOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              // 直接运行该策略的回测，不需要检查持仓
                              runSingleStrategyBacktest(strategy, null);
                            }}
                            style={{ marginRight: '8px' }}
                          >
                            运行回测
                          </Button>
                          <Button 
                            type="default" 
                            size="small"
                            onClick={(e) => {
                              e.stopPropagation();
                              // 查看该策略的交易记录
                              showStrategyTradeRecords(strategy);
                            }}
                            style={{ marginRight: '8px' }}
                          >
                            查看交易记录
                          </Button>
                          <Tag color={(strategy.return || 0) >= 0 ? 'green' : 'red'}>
                            {(strategy.return || 0) >= 0 ? '盈利' : '亏损'}
                          </Tag>
                        </div>
                      </div>
                    } 
                    key={index}
                  >
                    <Descriptions bordered size="small" column={1}>
                      <Descriptions.Item label="策略参数">
                        <pre>{JSON.stringify(strategy.parameters, null, 2)}</pre>
                      </Descriptions.Item>
                    </Descriptions>
                    
                    <Divider orientation="left">持仓明细</Divider>
                    
                    <div style={{ marginBottom: '10px', fontSize: '12px', color: '#666' }}>
                      提示：点击策略标题中的"运行回测"按钮可运行该策略的回测，"查看交易记录"按钮可查看该策略的交易历史
                    </div>
                    
                    {strategy.positions && strategy.positions.length > 0 ? (
                      <Table 
                        dataSource={strategy.positions} 
                        rowKey={(record, index) => index}
                        pagination={false}
                        size="small"
                        columns={[
                          { title: '股票代码', dataIndex: 'code', key: 'code' },
                          { title: '买入价格', dataIndex: 'price', key: 'price',
                            render: (text) => text ? text.toFixed(2) : '-' },
                          { title: '持仓日期', dataIndex: 'date', key: 'date', 
                            render: (text) => text ? moment(text).format('YYYY-MM-DD') : '-' }
                        ]} 
                      />
                    ) : (
                      <Empty description="暂无持仓" />
                    )}
                  </Panel>
                ))}
              </Collapse>
            </Card>
          </TabPane>
          
          <TabPane tab="回测结果" key="backtest">
            <Card 
              title="组合回测" 
              extra={
                <Space>
                  <DatePicker
                    placeholder="选择回测开始日期"
                    value={backTestStartDate}
                    onChange={(date) => {
                      console.log('选择的日期:', date);
                      setBackTestStartDate(date);
                    }}
                    format="YYYY-MM-DD"
                    style={{ width: '180px' }}
                  />
                  <Switch
                    checkedChildren="实盘"
                    unCheckedChildren="历史"
                    checked={useRealData}
                    onChange={setUseRealData}
                    title="选择回测数据源"
                  />
                  <Button 
                    type="primary" 
                    icon={<LineChartOutlined />} 
                    loading={backTestLoading}
                    disabled={backTestLoading}
                    onClick={() => {
                      setIsAutoBacktest(false);
                      runCombinationBacktest(selectedCombination);
                    }}
                  >
                    {backTestLoading ? '回测中...' : '运行回测'}
                  </Button>
                </Space>
              }
            >
              {!backTestResults && !backTestLoading && (
                <div style={{ textAlign: 'center', padding: '20px', color: '#666' }}>
                  <Text>切换到回测结果tab时会自动运行回测，或点击"运行回测"按钮手动执行</Text>
                </div>
              )}
              
              {backTestLoading && (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <Text>{isAutoBacktest ? '正在自动运行回测，请稍候...' : '正在运行回测，请稍候...'}</Text>
                </div>
              )}
              
              {backTestResults ? (
                <>
                  <Title level={4}>组合收益曲线</Title>
                  <ReturnsChart cumulativeReturns={backTestResults.combined_returns || []} />
                  
                  <Divider orientation="left">策略明细</Divider>
                  
                  <Collapse>
                    {backTestResults.strategy_results?.map((result, index) => (
                      <Panel 
                        header={`${result.strategy_name} (最终收益: ${result.final_return.toFixed(2)}%)`} 
                        key={index}
                        extra={
                          <Tag color={result.final_return >= 0 ? 'green' : 'red'}>
                            {result.final_return >= 0 ? '盈利' : '亏损'}
                          </Tag>
                        }
                      >
                        {result.error ? (
                          <Alert 
                            message="回测错误" 
                            description={result.error} 
                            type="error" 
                            showIcon 
                          />
                        ) : (
                          <>
                            <Descriptions bordered size="small" column={1}>
                              <Descriptions.Item label="策略参数">
                                <pre>{JSON.stringify(result.parameters, null, 2)}</pre>
                              </Descriptions.Item>
                            </Descriptions>
                            
                            {result.cumulative_returns && result.cumulative_returns.length > 0 && (
                              <>
                                <Divider orientation="left">收益曲线</Divider>
                                <ReturnsChart cumulativeReturns={result.cumulative_returns} />
                              </>
                            )}
                            
                            {result.trade_log && result.trade_log.length > 0 ? (
                              <>
                                <Divider orientation="left">交易记录</Divider>
                                <Table 
                                  dataSource={result.trade_log?.slice().reverse() || []} 
                                  rowKey={(record, index) => index}
                                  pagination={{ pageSize: 10 }}
                                  size="small"
                                  columns={[
                                    { title: '日期', dataIndex: 'date', key: 'date', 
                                      render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss') },
                                    { title: '类型', dataIndex: 'type', key: 'type',
                                      render: (text) => (
                                        <Tag color={text === 'buy' ? 'green' : 'red'}>
                                          {text === 'buy' ? '买入' : '卖出'}
                                        </Tag>
                                      ) },
                                    { title: '股票代码', dataIndex: 'code', key: 'code' },
                                    { title: '价格', dataIndex: 'price', key: 'price' },
                                    { title: '说明', dataIndex: 'desc', key: 'desc' }
                                  ]} 
                                />
                              </>
                            ) : (
                              <Empty description="暂无交易记录" />
                            )}
                          </>
                        )}
                      </Panel>
                    ))}
                  </Collapse>
                </>
              ) : (
                <Empty description="请点击运行回测按钮开始回测" />
              )}
            </Card>
          </TabPane>
        </Tabs>
      </div>
    );
  };
  
  useEffect(() => {
    // 默认设置为2015-01-01
    const defaultStartDate = moment('2015-01-01');
    setBackTestStartDate(defaultStartDate);
    console.log('默认开始日期设置为:', defaultStartDate.format('YYYY-MM-DD'));
  }, []);
  
  return (
    <div className="strategy-combination-container">
      <Row gutter={16}>
        <Col span={8}>
          <Card 
            title="策略组合列表" 
            extra={
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={() => showModal()}
              >
                新建组合
              </Button>
            }
          >
            <Table 
              dataSource={combinations} 
              columns={columns} 
              rowKey={(record, index) => index}
              loading={loading}
              pagination={{ pageSize: 10 }}
              size="small"
            />
          </Card>
        </Col>
        
        <Col span={16}>
          <Card title="组合详情">
            {renderCombinationDetails()}
          </Card>
        </Col>
      </Row>
      
      {/* 创建/编辑组合模态框 */}
      <Modal
        title={editingCombination ? "编辑策略组合" : "创建策略组合"}
        open={modalVisible}
        onOk={handleSave}
        onCancel={handleCancel}
        maskClosable={true}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="组合名称"
            rules={[{ required: true, message: '请输入组合名称' }]}
          >
            <Input placeholder="请输入组合名称" />
          </Form.Item>
          
          <Form.Item
            name="strategies"
            label="策略列表"
            rules={[
              { required: true, message: '请至少添加一个策略' },
              {
                validator: (_, value) => {
                  try {
                    const strategies = JSON.parse(value);
                    if (!Array.isArray(strategies)) {
                      return Promise.reject('策略列表必须是数组格式');
                    }
                    return Promise.resolve();
                  } catch (error) {
                    return Promise.reject('无效的JSON格式: ' + error.message);
                  }
                }
              }
            ]}
            initialValue="[]"
            help="请输入有效的JSON数组，每个策略对象应包含name和parameters属性"
            tooltip='策略数据必须是有效的JSON格式，例如：[{"name": "双均线策略", "parameters": {"ischeckhs300": true}}]'
          >
            <Input.TextArea 
              rows={10} 
              placeholder={'请输入JSON格式的策略数组，例如：\n[\n  {\n    "name": "双均线策略",\n    "parameters": {\n      "ischeckhs300": true,\n      "hs300_limit": 30,\n      "backCycle": "day",\n      "codes": ["000016.XSHG", "000852.XSHG"],\n      "increaseday_range": 21,\n      "highday_range": 25,\n      "lowday_range": 17,\n      "sortType": 1,\n      "tradeType": 1\n    }\n  }\n]'}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StrategyCombination; 